//
//  UIColor+CYColorHex.m
//  CYBaseKit
//
//  Created by admin on 2022/7/28.
//

#import "UIColor+CYColorHex.h"

@implementation UIColor (CYColorHex)
#pragma mark - UIColor from Hex

+ (UIColor *)cy_colorFromHex:(NSString *)hexString {
    return [self cy_colorFromHex:hexString andAlpha:1.0];
}

+ (UIColor *)cy_colorFromHex:(NSString *)hexString andAlpha:(CGFloat)alpha {
    unsigned rgbValue = 0;
    NSString *fixHexString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    if (fixHexString.length < 1) {
        return [UIColor blackColor];
    }
    NSScanner *scanner = [NSScanner scannerWithString:fixHexString];
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0 green:((rgbValue & 0xFF00)
            >> 8) / 255.0   blue:(rgbValue & 0xFF) / 255.0 alpha:alpha];
}

#pragma mark - Hex from UIColor

+ (NSString *)cy_hexFromColor:(UIColor *)color {
    NSArray *colorArray = [self cy_RGBA_ArrayFromColor:color];
    int r = [colorArray[0] floatValue] * 255;
    int g = [colorArray[1] floatValue] * 255;
    int b = [colorArray[2] floatValue] * 255;
    NSString * red = [NSString stringWithFormat:@"%02x", r];
    NSString * green = [NSString stringWithFormat:@"%02x", g];
    NSString * blue = [NSString stringWithFormat:@"%02x", b];
    return [NSString stringWithFormat:@"#%@%@%@", red, green, blue];
}

#pragma mark - RGBA from UIColor

+ (NSArray *)cy_RGBA_ArrayFromColor:(UIColor *)color {
    // Takes a UIColor and returns R,G,B,A values in NSNumber form
    CGFloat r = 0, g = 0, b = 0, a = 0;
    if ([color respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
        [color getRed:&r green:&g blue:&b alpha:&a];
    } else {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        r = components[0];
        g = components[1];
        b = components[2];
        a = components[3];
    }
    return @[[NSNumber numberWithFloat:r], [NSNumber numberWithFloat:g], [NSNumber numberWithFloat:b], [NSNumber numberWithFloat:a]];
}

#pragma mark - HSBA from UIColor

+ (NSArray *)cy_HSBA_ArrayFromColor:(UIColor *)color {
    // Takes a UIColor and returns Hue,Saturation,Brightness,Alpha values in NSNumber form
    CGFloat h = 0, s = 0, b = 0, a = 0;

    if ([color respondsToSelector:@selector(getHue:saturation:brightness:alpha:)]) {
        [color getHue:&h saturation:&s brightness:&b alpha:&a];
    }
    return @[[NSNumber numberWithFloat:h], [NSNumber numberWithFloat:s], [NSNumber numberWithFloat:b], [NSNumber numberWithFloat:a]];
}

@end
